package ua.kharkov.knure.pereverziev.diploma.web.command;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import ua.kharkov.knure.pereverziev.diploma.db.DAOServices.UserService;
import ua.kharkov.knure.pereverziev.diploma.db.entity.User;

public class LoginCommand implements Command {

	private static final Logger log = Logger.getLogger(LoginCommand.class);

	@Override
	public String execute(final HttpServletRequest request,
			final HttpServletResponse response) throws IOException,
			ServletException {
		log.debug("Command starts");

		final HttpSession session = request.getSession();

		// obtain airport and password from the request
		// DBManager manager = DBManager.getInstance();
		final String email = request.getParameter("email");
		log.trace("Request parameter: email --> " + email);

		final String password = request.getParameter("password");
		// TODO REMOVE FROM THE PRODUCTION
		log.trace("Request parameter: password --> " + password);

		// error handler
		// set forward to error page
		String forward = null;
		final StringBuilder errorMessage = new StringBuilder();

		if (password.isEmpty() || email.isEmpty()) {
			errorMessage.append("Login or password is empty\n");
		} else {

			final UserService userService = new UserService();
			final User user = userService.logIn(email, password);
			log.debug("Found in DB: user --> " + user);

			if (user == null || !password.equals(user.getPassword())) {
				errorMessage
						.append("Cannot find user with such login and password");
			} else {

				log.debug("Found in DB: Status --> " + user.getStatus());
				session.setAttribute("user", user);
				log.debug("Set the session attribute: user --> " + user);

				session.setAttribute("isAdministration", false);

				forward = "/WEB-INF/jsp/mainPage.jsp";

			}
		}

		// go to the error page if error message not empty
		if (errorMessage.length() != 0) {
			session.setAttribute("errorMessage", errorMessage);
			forward = "/login.jsp?error=" + errorMessage.toString();
			log.trace("Set the session attribute: errorMessage --> "
					+ errorMessage);
		}

		log.debug("Command finished");

		session.setAttribute("lastPage", forward);
		log.trace("Session attribute: lastPage --> " + forward);

		return forward;
	}
}
